package com.wys.spring.mybatisplus.generator;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.wys.api.utils.DateTimeUtils;
import com.wys.spring.ApplicationContextHolder;
import com.wys.spring.mybatisplus.service.BaseService;
import com.wys.utils.StringUtils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MybatisPlusCodeGenerator {


    //todo 待完善
    public FastAutoGenerator buildMybatisCodeGenerator(MybatisPlusGeneratorProperties mybatisPlusGeneratorProperties) {
        AbstractRoutingDataSource abstractRoutingDataSource = ApplicationContextHolder.context.getBean(AbstractRoutingDataSource.class);
        DruidDataSource dataSource = (DruidDataSource) abstractRoutingDataSource.getResolvedDataSources().values().stream().findFirst().get();
        FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
        fastAutoGenerator.globalConfig(s -> s.author(mybatisPlusGeneratorProperties.getAuthor()).enableSwagger().commentDate(DateTimeUtils.DEFAULT_DATE_TIME_FORMAT)
                .dateType(DateType.TIME_PACK)
                .disableOpenDir().outputDir(mybatisPlusGeneratorProperties.getOutDir()).build());
        fastAutoGenerator.packageConfig(s -> s.controller(mybatisPlusGeneratorProperties.getController()).moduleName(mybatisPlusGeneratorProperties.getModelName())
                .mapper(mybatisPlusGeneratorProperties.getMapper())
                .entity(mybatisPlusGeneratorProperties.getEntity())
                .parent(mybatisPlusGeneratorProperties.getParentName())
                .serviceImpl(mybatisPlusGeneratorProperties.getService())
                .xml(mybatisPlusGeneratorProperties.getMapperXml())
                .build());
        fastAutoGenerator.strategyConfig(s -> s.serviceBuilder().superServiceImplClass(BaseService.class).build());
        fastAutoGenerator.strategyConfig(s -> s.addInclude(org.apache.commons.lang3.StringUtils.isNotBlank(mybatisPlusGeneratorProperties.getTables()) ? mybatisPlusGeneratorProperties.getTables().split(",") : new String[]{})
                .addExclude(StringUtils.isEmpty(mybatisPlusGeneratorProperties.getExcludes()) ? new String[]{} : mybatisPlusGeneratorProperties.getExcludes().split(","))
                .addTablePrefix(mybatisPlusGeneratorProperties.getPrefixTableName()));
        fastAutoGenerator.templateEngine(new FreemarkerTemplateEngine());
        return fastAutoGenerator;
    }



}
